package org.ourgrid.discoveryservice.business.requester;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.discoveryservice.PeerStatusChangeUtil;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceDAO;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceDAOFactory;
import org.ourgrid.discoveryservice.business.messages.DiscoveryServiceControlMessages;
import org.ourgrid.discoveryservice.request.GetRemoteWorkerProvidersRequestTO;
import org.ourgrid.discoveryservice.response.DSClientHereIsRemoteWorkerProvidersListResponseTO;
import org.ourgrid.discoveryservice.response.DSHereIsRemoteWorkerProvidersListResponseTO;

public class GetRemoteWorkerProvidersRequester implements RequesterIF<GetRemoteWorkerProvidersRequestTO>{
	
	public List<IResponseTO> execute(GetRemoteWorkerProvidersRequestTO request) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		DiscoveryServiceDAO dsDao = DiscoveryServiceDAOFactory.getInstance().getDiscoveryServiceDAO();
		
		String clientUserAtServer = request.getClientUserAtServer();
		
		if (!dsDao.isLogged(clientUserAtServer)) {
			responses.add((new LoggerResponseTO(DiscoveryServiceControlMessages.getClientNotLoggedMessage(clientUserAtServer), LoggerResponseTO.DEBUG)));
			
			joinCommunity(responses, clientUserAtServer);
		}
		
		DSClientHereIsRemoteWorkerProvidersListResponseTO to = new DSClientHereIsRemoteWorkerProvidersListResponseTO();
		to.setStubAddress(request.getClientAddress());
		to.setWorkerProviders(dsDao.getOnlinePeers());
		
		responses.add(to);
		
		return responses;
	}
	
	private void joinCommunity(List<IResponseTO> responses, String clientUserAtServer) {
		
		DiscoveryServiceDAO dsDao = DiscoveryServiceDAOFactory.getInstance().getDiscoveryServiceDAO();
		dsDao.peerIsUp(clientUserAtServer);
		
		List<String> onlinePeers = dsDao.getOnlinePeers();
		
		List<String> dsAddresses = dsDao.getDiscoveryServicesAddresses();
		
		for (String address : dsAddresses) {
			DSHereIsRemoteWorkerProvidersListResponseTO to = new DSHereIsRemoteWorkerProvidersListResponseTO();
			to.setStubAddress(address);
			to.setWorkerProviders(onlinePeers);
			
			responses.add(to);
		}
		
		PeerStatusChangeUtil.peerIsUp(clientUserAtServer);
	}
	
}
